import {
	remote_takeSound,
	remote_takePhotos
} from '@/common/api/index.js'

import {
	cameraPermissiong,
} from "@/common/utils.js"


const recorderManager = uni.getRecorderManager();
const innerAudioContext = uni.createInnerAudioContext();
innerAudioContext.autoplay = true;

module.exports = {
	data() {
		return {

		}
	},
	async created() {
		uni.$on('takePhoto', async (topic, data) => {
			await this.startPreview(data);
			this.successSendMqt('refresh_photo', topic);
		})
		uni.$on('takeAudio', async (topic, data) => {
			await this.getRecord(data);
			this.successSendMqt('refresh_audio', topic);
		})
	},
	methods: {
		async startPreview(dataInfo) {
			let that = this;
			let status = await cameraPermissiong();
			if (status != 1) return
			return new Promise((resolve, reject) => {
				if (uni.getSystemInfoSync().platform == 'android') {
					that.$refs.myComponent.startPreview({
						cameraId: dataInfo.cameraId
					}, async (res) => {
						await that.takePhotoPath(dataInfo);
						resolve()
					});
				} else {
					that.$refs.myComponent.startPreview({
						cameraId: dataInfo.cameraId
					}, async (res) => {
						await that.takePhotoPath(dataInfo);
						resolve()
					});
				}
			})
		},
		takePhotoPath(dataInfo) {
			let that = this;
			return new Promise((resolve, reject) => {
				const dir = "_doc/pic";
				let path = plus.io.convertLocalFileSystemURL(dir);
				that.$refs.myComponent.takePhoto({
					savePath: path,
					outputMode: 1,
				}, async (res) => {
					// 压缩图片
					let compressPath = await new Promise((resolve, reject) => {
						uni.compressImage({
							src: res.data, // 图片路径
							quality: 80, // 压缩质量，范围0～100，数值越小，质量越低，压缩率越高（该范围仅对jpg有效）
							success: (compressRes) => {
								console.log('压缩成功', compressRes
									.tempFilePath);
								// 上传压缩后的图片
								resolve(compressRes.tempFilePath);
							},
							fail: (err) => {
								console.error('图片压缩失败', err);
								reject(err);
							}
						});
					})
					// 上传图片
					let uploadRes = await remote_takePhotos({
						filePath: compressPath,
						user_id: dataInfo.user_id,
						type: dataInfo.cameraId == 0 ? 1 : 0
					})
					if (uploadRes.code == 1) {
						uni.removeSavedFile({
							filePath: res.data,
						})
					} else {

					}
					that.$refs.myComponent.stopPreview();
					resolve();
				});
			})
		},
		getRecord(dataInfo) {
			return new Promise((resolve, reject) => {
				recorderManager.start({
					duration: 20000,
					hideTips: true
				});
				recorderManager.onStop(async (callback) => {
					console.log('录音结束');
					let res = await remote_takeSound({
						filePath: callback.tempFilePath,
						user_id: dataInfo.user_id,
					})
					if (res.code == 1) {
						resolve();
					}
				})
			})
		}
	}
}